import { memo, useCallback } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { Button, Form, Input, message } from 'antd';
import * as yup from 'yup';
import { alphaNumericRegexString } from '@/constants/regexp';
import { useAuthStore } from '@/store/authStore';
import { yupResolver } from '@hookform/resolvers/yup';
import {
  labelCol,
  validateMessage,
  wrapperCol,
} from '@/components/AddressFormModal';
import ProfileContainer from '@/components/ProfileContainer';
import RxButton from '@/components/RxForm/RxButton';
import RxPassword from '@/components/RxForm/RxPassword';
import { tooltip } from '@/pages/Login/components/EmailRegisterForm';

const schema = yup
  .object({
    oldPassword: yup.string().required(),
    password: yup
      .string()
      .matches(alphaNumericRegexString, '密码只能包含数字和字母')
      .min(8)
      .max(16),
    passwordConfirmation: yup
      .string()
      .oneOf([yup.ref('password')], '确认密码错误')
      .required(),
  })
  .required();

const defaultValues: API.ChangePasswordParams = {
  password: '',
  passwordConfirmation: '',
  oldPassword: '',
};

const ChangePwdPage: FC<PropsWithChildren<{}>> = () => {
  const { control, handleSubmit, trigger, resetField, reset } =
    useForm<API.ChangePasswordParams>({
      resolver: yupResolver(schema),
      defaultValues,
      mode: 'all',
      criteriaMode: 'all',
    });

  const {
    changePwd: { changePwd, loading },
  } = useAuthStore();

  const onSubmit: SubmitHandler<API.ChangePasswordParams> = useCallback(
    (values) => {
      changePwd(values)
        .then(() => {
          reset();
        })
        .catch(() => {
          message.error('服务器错误');
        });
    },
    []
  );
  return (
    <ProfileContainer title={'修改密码'}>
      <div className={"p-6 mt-10 flex-justify-items-center"}>
        <Form
          onFinish={handleSubmit(onSubmit)}
          validateMessages={validateMessage}
          labelCol={labelCol}
          wrapperCol={wrapperCol}
          className={"w-96"}
        >
          <RxPassword
            key={'oldPassword'}
            name={'oldPassword'}
            placeholder={'请输入原密码'}
            control={control}
            tooltip={tooltip}
          />
          <RxPassword
            key={'password'}
            name={'password'}
            placeholder={'请输入新密码'}
            control={control}
            tooltip={tooltip}
          />
          <RxPassword
            key={'passwordConfirmation'}
            name={'passwordConfirmation'}
            placeholder={'确认密码'}
            control={control}
            tooltip={tooltip}
          />
          <Form.Item className={'text-center'}>
            <RxButton loading={loading} type={"primary"} >修改密码 </RxButton>
          </Form.Item>
        </Form>
      </div>
    </ProfileContainer>
  );
};

export default memo(ChangePwdPage);
